package com.drd.dt.filter;

import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (request.getServletPath().startsWith("/api/v2/htsq") && !request.getServletPath().equals("/api/v2/htsq/user/wxLogin")
                && !request.getServletPath().equals("/api/v2/htsq/user/codeLogin")) {
            final String token = request.getParameter("token_id");
            final String userId = request.getParameter("user_id");
            if (!StringUtils.isEmpty(userId)) {
                User user = userMapper.selectById(Integer.valueOf(userId));
                if (null != user) {
                    // controller或者service中获取用户信息时，直接使用 【UserThreadLocal.get().getXXX()】
                    UserThreadLocal.set(user);
                    Integer status = user.getStatus();
                    if (!StringUtils.isEmpty(status) && status == 0) {//账号被冻结
                        throw new BussinessException(BizExceptionEnum.OT_USER_ILLEGAL);
                    }
                    if (!StringUtils.isEmpty(token)) {//token校验
                        String tokenId = user.getToken();
                        if (!token.equals(tokenId)) {
                            throw new BussinessException(BizExceptionEnum.OT_LOGIN_ERROR);
                        }
                    }
                } else {
                    throw new BussinessException(BizExceptionEnum.OT_USER_ERROR);
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        UserThreadLocal.set(null);
    }

}